<?php defined('SYSPATH') or die('No direct script access.');

class ORM extends Kohana_ORM {
    
    public function getNextOrderNo(){
        try{
            $table = $this->_table_name;
            $q = "select max(order_no) as res from $table";
            $r = DB::query(Database::SELECT, $q)->execute();
            $x = $r->as_array();
            $res = $x[0]['res'];
            ++$res;
        }catch(Exception $e){
            $res = null;
        }
        return $res;
    }
    
    public function create(Validation $validation = NULL) {
        $order_no = $this->getNextOrderNo();
        if($order_no !== null){
            $this->order_no = $order_no;
        }
        parent::create($validation);
    }
    
    public function swapOrderWith($id){
        if(!$this->id){
            throw new Exception('swapOrderWith: no curr_id');
        }
        
        if(!$this->order_no){
//            throw new Exception('No order_no column');
        }
        
        $model = clone $this;
        $model->clear();
        $model->where('id','=',$id)->find();
        
        $new_order_no = $model->order_no;
        $old_order_no = $this->order_no;
        
        $this->order_no = $new_order_no;
        $this->save();
        $model->order_no = $old_order_no;
        $model->save();
        
        return $this->order_no;
    }
    
    
    public function swapOrderWithNumber($new_order_no){
        if(!($new_order_no > 0)){
            throw new Exception('Nieprawidlowy $new_order_no');
        }
        if(!$this->_table_name){
            throw new Exception('Brak $this->_table_name');
        }
        if($new_order_no == $this->order_no){
            return;
        }
        
        $model = clone $this;
        $model->clear();
        
        $r = $model->where('order_no','=',$new_order_no)->find_all();
        
        if($r->count()){
            $q = "update {$this->_table_name} set order_no=order_no+1 where order_no >= {$new_order_no}";
            $r = DB::query(Database::UPDATE, $q)->execute();
        }

        $this->order_no = $new_order_no;
        $this->save();
    }
    
    /**
     *
     * @param Array of Orm objects
     * @return Array of arrays 
     */
    public static function damnArray($result){      // ORM array
        foreach($result as $k=>$v){
            $res[$k] = $v->as_array();
        }
        return $res;
    }
}
